<script setup>
import { cancelOrderAPI, getUserOrder, handleDelOrderAPI, receiveItemAPI } from "@/api/user";
import { ElMessage } from "element-plus";
import { onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { formatTime } from "@/utils/format";
import OrderCountdown from "../components/OrderCountdown.vue"
import { Plus, Loading } from '@element-plus/icons-vue'
import { submitCommentAPI, uploadAPI } from "@/api/comment";
import { ElLoading } from 'element-plus'
const router = useRouter()
// tab列表
const tabTypes = [
    { name: "all", label: "全部订单" },
    { name: "unpay", label: "待付款" },
    { name: "deliver", label: "待发货" },
    { name: "receive", label: "待收货" },
    { name: "comment", label: "待评价" },
    { name: "complete", label: "已完成" },
    { name: "cancel", label: "已取消" }
]
// 订单列表s
const orderList = ref([])
const params = ref({
    orderState: 0,
    page: 1,
    pageSize: 2
})
const loading = ref(true)
const total = ref(0)
const getOrderList = async () => {
    loading.value = true
    const { result } = await getUserOrder(params.value)
    orderList.value = result.items
    //console.log(orderList)
    total.value = result.counts
    loading.value = false

}
onMounted(() => {
    getOrderList()

})
const handleChange = (type) => {
    params.value.orderState = type
    params.value.page = 1
    getOrderList()
}
const handlePageChange = (page) => {
    params.value.page = page
    console.log(params.value.page)
    getOrderList()
}
const goDetail = (id, state) => {//没有成功
    console.log("跳转到详情页")
    router.push({
        path: '/checkout',
        query: {
            id,
            state
        }
    })
}
const handleCancel = async (id) => {
    console.log(id)
    await cancelOrderAPI(id).then(() => {
        ElMessage.success('取消订单成功')
    })
    getOrderList()
}

const goPay = (id) => {
    console.log(id)

    router.push({
        path: '/pay',
        query: {
            id
        }
    })

}
const finishIds = ref([])
const handleFinish = (id) => {
    console.log(id)
    finishIds.value.push(id)
}
const handleDel = async (id) => {
    await handleDelOrderAPI(id).then(() => {
        ElMessage.success('删除订单成功')
    })
    console.log('handleDel' + id);

    getOrderList()
}

const receiveItem = async (id) => {
    console.log('receiveItem');
    await receiveItemAPI(id).then(() => {
        ElMessage.success('收货成功')
    })
    getOrderList()
}

const commentVisible = ref(false)
const form = ref({
    orderId: '',
    itemId: '',
    content: '',
    images: [],
    rate: 0
})
const ruleFormRef = ref(null)
const commentItem = ref({})
const goComment = (id, item) => {
    form.value.orderId = id
    form.value.itemId = item.itemId
    commentItem.value = item
    commentVisible.value = true
}

const rule = {
    content: [
        { required: false, message: '请输入评价内容', trigger: 'change' },
        { min: 1, max: 200, message: '评价内容在1-200字之间', trigger: 'change' }
    ],
    rate: [
        { required: true, message: '请给商品评分', trigger: 'change' },
        {
            validator(rule, value, callback) {
                if (value > 0 && value <= 5) {
                    callback()
                } else {
                    callback(new Error('请给商品评分'))
                }
            }
        }
    ]
}
const handleClose = () => {
    commentVisible.value = false
    ruleFormRef.value.resetFields()
    commentItem.value = {}
    selectedFiles.value= []
}
const handleSubmit = () => {
    const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    ruleFormRef.value.validate(async (valid) => {
        if (valid) {
            try {
                await customUpload()
            } catch (error) {
                ElMessage.warning('评价失败')
                return
            }
            await submitCommentAPI(form.value).then(() => {
                ElMessage.success('评价成功')
                handleClose()
                getOrderList()
            })
        } else {
            ElMessage.warning('请输入完整评价')
            console.log(form.value);
        }
    }
    )
    loading.close()
}

//图片

// 存储选择的文件数组
const selectedFiles = ref([]);
// 获取 el-upload 组件的引用
const uploadRef = ref(null);
const onSelectFile = (file, fileList) => {
    selectedFiles.value = fileList.map(item => item.raw);
}

// 自定义文件上传方法
const customUpload = async () => {
    if (selectedFiles.value.length > 0) {
        // 创建 FormData 对象
        const formData = new FormData();
        selectedFiles.value.forEach((file) => {
            formData.append(`files`, file);
        });
        await uploadAPI(formData)
            .then((response) => {
                form.value.images = response.result
                selectedFiles.value = [];
                uploadRef.value.clearFiles();
                ElMessage.success('上传成功');
            })
            .catch((error) => {
                ElMessage.error('上传失败');
                throw error;
            });
    }
};

const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handleRemove = (uploadFile, uploadFiles) => {
    console.log(uploadFile, uploadFiles)
    selectedFiles.value = uploadFiles.map(item => item.raw);
}


const handlePictureCardPreview = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url
    dialogVisible.value = true
}

// 上传前的验证逻辑
const beforeUpload = (rawFile) => {
    // 允许的文件类型
    const allowedTypes = ['image/jpeg', 'image/png'];
    // 允许的最大文件大小（10MB）
    const maxSize = 10 * 1024 * 1024;
    // 检查文件类型
    if (!allowedTypes.includes(rawFile.type)) {
        ElMessage.error('仅支持 JPG 和 PNG 格式的图片！');
        return false;
    }
    // 检查文件大小
    if (rawFile.size > maxSize) {
        ElMessage.error('图片大小不能超过 10MB！');
        return false;
    }
    // 文件类型和大小都符合要求，允许上传
    return true;
};
</script>

<template>
    <div class="order-container">
        <div v-if="commentVisible" class="overlay"></div>
        <el-tabs v-model="params.orderState" @tab-change="handleChange">
            <!-- tab切换 -->
            <el-tab-pane v-for="item in tabTypes" :key="item.name" :label="item.label" />

            <div class="main-container" v-loading="loading">
                <div class="holder-container" v-if="orderList.length === 0">
                    <el-empty description="暂无订单数据" />
                </div>
                <div v-else>
                    <!-- 订单列表 -->
                    <div class="order-item" v-for="order in orderList" :key="order.id">
                        <div class="head">
                            <span>下单时间：{{ formatTime(order.createTime) }}</span>
                            <span>订单编号：{{ order.id }}</span>
                            <!-- 未付款，倒计时时间还有 -->
                            <OrderCountdown v-if="order.orderState === 1 && order.countdown > 0"
                                :initial-time="order.countdown" :orderId="order.id" @finish="handleFinish"
                                class="down-time" />
                            <span v-if="[4, 5, 6].includes(order.orderState)" class="del"
                                @click="handleDel(order.id)">删除订单</span>
                        </div>
                        <div class="body">
                            <div class="column goods">
                                <ul>
                                    <li v-for="item in order.skus" :key="item.id">
                                        <a class="image" href="javascript:;"
                                            @click="$router.push('/detail/' + item.itemId)">
                                            <img :src="item.image" alt="" />
                                        </a>
                                        <div class="info">
                                            <p class="name ellipsis-2">
                                                {{ item.name }}
                                            </p>
                                            <p class="attr ellipsis">
                                                <span>{{ item.attrsText }}</span>
                                            </p>
                                        </div>
                                        <div class="price">¥{{ item.realPay }}</div>
                                        <div class="count">x{{ item.count }}</div>
                                        <div class="column state">
                                            <p>{{ tabTypes[order.orderState].label }}</p>
                                            <p v-if="order.orderState === 3">
                                                <a href="javascript:;" class="green">查看物流</a>
                                            </p>
                                            <p v-if="order.orderState === 4">
                                                <a href="javascript:;" class="green"
                                                    @click="goComment(order.id, item)">评价商品</a>
                                            </p>
                                            <p v-if="order.orderState === 5"
                                                @click="$router.push('/comment/' + item.itemId)">
                                                <a href="javascript:;" class="green">查看评价</a>
                                            </p>
                                        </div>
                                    </li>
                                </ul>
                            </div>

                            <div class="column amount">
                                <p class="red">¥{{ order.payMoney }}</p>
                                <p>（含运费：¥{{ order.postFee }}）</p>
                                <p>在线支付</p>
                            </div>
                            <div class="column action">
                                <el-button v-if="order.orderState === 1 && !finishIds.includes(order.id)" type="primary"
                                    size="small" @click="goPay(order.id)">
                                    立即付款
                                </el-button>
                                <el-button v-if="order.orderState === 3" type="primary" size="small"
                                    @click="receiveItem(order.id)">
                                    确认收货
                                </el-button>
                                <p @click="goDetail(order.id, order.state)"><a href="javascript:;">查看详情</a></p>
                                <p v-if="[2, 3, 4, 5].includes(order.orderState)">
                                    <a href="javascript:;">再次购买</a>
                                </p>
                                <p v-if="[4, 5].includes(order.orderState)">
                                    <a href="javascript:;">申请售后</a>
                                </p>
                                <p v-if="order.orderState === 1" @click="handleCancel(order.id)"><a
                                        href="javascript:;">取消订单</a></p>
                            </div>
                        </div>
                    </div>
                    <!-- 分页 -->
                    <div class="pagination-container">
                        <el-pagination @current-change="handlePageChange" :total="total" :page-size="params.pageSize"
                            background layout="prev, pager, next" />
                    </div>
                </div>
            </div>

        </el-tabs>


        <div class="comment" v-if="commentVisible">
            <div class="add-box-header">
                <span class="add-box-title">评论商品</span>
                <span class="close-icon" @click="handleClose()">×</span>
            </div>
            <div class="column goods" style="margin-top: 10px;">
                <ul>
                    <li>
                        <a class="image" href="javascript:;" @click="$router.push('/detail/' + commentItem.itemId)">
                            <img :src="commentItem.image" alt="" />
                        </a>
                        <div class="info">
                            <p class="name ellipsis-2">
                                {{ commentItem.name }}
                            </p>
                            <p class="attr ellipsis">
                                <span>{{ commentItem.attrsText }}</span>
                            </p>
                        </div>
                        <div class="price">¥{{ commentItem.realPay }}</div>
                        <div class="count">x{{ commentItem.count }}</div>
                    </li>
                </ul>
            </div>
            <el-form :rules="rule" ref="ruleFormRef" :model="form" status-icon>
                <el-form-item label="评价商品" prop="rate">
                    <el-rate v-model="form.rate" :max="5" style="margin-top: 10px;" />
                </el-form-item>
                <el-form-item label="评价内容" prop="content">
                    <el-input type="textarea" :rows="4" placeholder="请输入内容" v-model="form.content" />
                </el-form-item>
                <el-form-item label="评价图片" prop="images">

                    <el-upload ref="uploadRef" list-type="picture-card" :on-change="onSelectFile" multiple="true"
                        :auto-upload="false" :on-preview="handlePictureCardPreview" :on-remove="handleRemove"
                        :http-request="customUpload" :limit="9" :before-upload="beforeUpload">
                        <el-icon>
                            <Plus />
                        </el-icon>
                        <template #tip>
                            <div class="el-upload__tip text-red">
                                最多9个文件
                            </div>
                        </template>
                    </el-upload>

                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSubmit()">提交评价</el-button>
                </el-form-item>
            </el-form>

        </div>
        <el-dialog v-model="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
    </div>

</template>

<style scoped lang="scss">
.order-container {
    padding: 10px 20px;

    .pagination-container {
        display: flex;
        justify-content: center;
    }

    .main-container {
        min-height: 500px;

        .holder-container {
            min-height: 500px;
            display: flex;
            justify-content: center;
            align-items: center;
        }
    }
}

.order-item {
    margin-bottom: 20px;
    border: 1px solid #f5f5f5;

    .head {
        height: 50px;
        line-height: 50px;
        background: #f5f5f5;
        padding: 0 20px;
        overflow: hidden;

        span {
            margin-right: 20px;

            &.down-time {
                margin-right: 0;
                float: right;

                i {
                    vertical-align: middle;
                    margin-right: 3px;
                }

                b {
                    vertical-align: middle;
                    font-weight: normal;
                }


            }
        }

        .del {
            margin-right: 0;
            float: right;
            color: #999;

            &:hover {
                color: black;
                cursor: pointer;
            }
        }
    }

    .body {
        display: flex;
        align-items: stretch;


    }
}

/* 遮罩层样式 */
.overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    /* 半透明黑色背景 */
    z-index: 999;
    /* 确保遮罩层在其他元素之上 */
}

.column {
    border-left: 1px solid #f5f5f5;
    text-align: center;
    padding: 20px;

    >p {
        padding-top: 10px;
    }

    &:first-child {
        border-left: none;
    }

    &.goods {
        flex: 1;
        padding: 0;
        align-self: center;

        ul {
            li {
                border-bottom: 1px solid #f5f5f5;
                padding: 10px;
                display: flex;

                &:last-child {
                    border-bottom: none;
                }

                .image {
                    width: 70px;
                    height: 70px;
                    border: 1px solid #f5f5f5;
                }

                .info {
                    width: 220px;
                    text-align: left;
                    padding: 0 10px;

                    p {
                        margin-bottom: 5px;

                        &.name {
                            height: 38px;
                        }

                        &.attr {
                            color: #999;
                            font-size: 12px;

                            span {
                                margin-right: 5px;
                            }
                        }
                    }
                }

                .price {
                    width: 100px;
                }

                .count {
                    width: 80px;
                }
            }
        }
    }

    &.state {
        width: 120px;

        .green {
            color: $xtxColor;
        }
    }

    &.amount {
        width: 200px;

        .red {
            color: $priceColor;
        }
    }

    &.action {
        width: 140px;

        a {
            display: block;

            &:hover {
                color: $xtxColor;
            }
        }
    }
}

.comment {
    position: absolute;
    top: 30%;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: #fff;
    border: 1px solid #ccc;
    border-radius: 8px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    padding: 20px;
    width: 600px;

    z-index: 1001;

    .add-box-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 5%;
        background-color: #f5f5f5;
        border-top-left-radius: 8px;
        border-top-right-radius: 8px;
    }

    .add-box-title {
        margin: 0;
        font-size: 18px;
        font-weight: bold;
    }

    .close-icon {
        cursor: pointer;
        font-size: 20px;
        font-weight: bold;
    }
}

.uploaded-images {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    /* 图片之间的间距 */
    margin-bottom: 10px;
    /* 与上传组件的间距 */
}

.uploaded-image {
    width: 100px;
    /* 图片宽度 */
    height: 100px;
    /* 图片高度 */
    object-fit: cover;
    /* 图片填充方式 */
    border-radius: 4px;
    /* 图片圆角 */
}
</style>